package com.tiancikeji.zaoke.app.service.food.impl;

import java.util.HashSet;
import java.util.Set;

import com.tiancikeji.zaoke.app.dao.food.FoodDao;
import com.tiancikeji.zaoke.app.model.food.Food;
import com.tiancikeji.zaoke.app.service.food.FoodService;
import com.tiancikeji.zaoke.app.util.LocalCaches;

@SuppressWarnings("unchecked")
public class FoodServiceImpl implements FoodService{
	
	private FoodDao foodDao;
	
	private long expireTime;

	public Food getFoodById(long foodId) {
		Set<Food> foods = getAllFoods();
		
		if(foods != null && foods.size() > 0)
			for(Food food : foods)
				if(food.getId() == foodId)
					return food;
		
		return null;
	}

	public Set<Food> getAllActiveFoods(){
		Set<Food> foods = getAllFoods();
		Set<Food> result = new HashSet<Food>();
		
		if(foods != null && foods.size() > 0)
			for(Food food : foods)
				if(food.getState() == Food.STATE_ACTIVE)
					result.add(food);
		
		return result;
	}

	private Set<Food> getAllFoods(){
		Set<Food> foods = (Set<Food>)LocalCaches.get(LocalCaches.ZAOKE_CACHE_ACTIVE_FOODS_KEY, System.currentTimeMillis(), expireTime);
		
		if(foods == null){
			foods = foodDao.getFoodsByState(new Integer[]{Food.STATE_ACTIVE, Food.STATE_INACTIVE});

			if(foods != null && foods.size() > 0)
				LocalCaches.set(LocalCaches.ZAOKE_CACHE_ACTIVE_FOODS_KEY, foods, System.currentTimeMillis());
		}
		
		return foods;
	}

	public FoodDao getFoodDao() {
		return foodDao;
	}

	public void setFoodDao(FoodDao foodDao) {
		this.foodDao = foodDao;
	}

	public long getExpireTime() {
		return expireTime;
	}

	public void setExpireTime(long expireTime) {
		this.expireTime = expireTime;
	}
}
